import Taro from '@tarojs/taro'
const ip = "http://192.168.1.4:7001/"
// const ip = "https://yuncommunity.com:7001/"
const host = ip + "v1/api/"

export function request(api, params, success, fail) {
  if (!params) {
    params = {}
  }
  Taro.getStorage({
    key: "token",
    success: res => {
      params.token = res.data
      startRequest(api, params, success, fail)
    },
    fail: res => {
      console.log(res)
      startRequest(api, params, success, fail)
    }
  })
}

function startRequest(api, params, success, fail) {
  Taro.request({
    url: host + api,
    data: params,
    success: res => {
      if (res.data.code == 0) {
        if (success) {
          success(res.data.data)
        }
      } else {
        if (fail) {
          fail(res.data.data, res.data.code)
        }
      }
    },
    fail: res => {
      console.log("fail", res)
    }
  })
}

export function formatDate(time) {
  if (time && time.length > 10) {
    return time.substring(0, 10)
  }
  return ""
}

export function randomString(len) {
  let text = "";

  let charset = "abcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < len; i++)
    text += charset.charAt(Math.floor(Math.random() * charset.length));

  return text;
}
